package kr.co.happenstance;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import kr.co.happenstance.lib.MatchingLib;
import kr.co.happenstance.lib.MemberLib;
import kr.co.happenstance.lib.vo.LibResultVo;
import kr.co.happenstance.lib.vo.MatchingAcceptYnResultVo;
import kr.co.happenstance.lib.vo.MatchingInfoResultVo;
import kr.co.happenstance.lib.vo.MemberLastLocationResultVo;
import kr.co.happenstance.util.Util;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class WaitingRecipientActivity extends BaseActivity implements View.OnClickListener{
	protected final String TAG = "<<<WaitingRecipientActivity>>>";
	
	/**
	 * push 받은 매칭요청테이블 시퀀스
	 */
	private int matchingRequestSeq;
	
	/**
	 * 요청자 동의 여부
	 */
	private String matchingAcceptYn = "N";
	
	/**
	 * 상대방 프로필 정보 보기 가능 여부 
	 */
	private String profileYn;
	
	/**
	 * 요청자 ID
	 */
	private String requestorId;
	
	
	private Calendar promiseDate;
	
	
	protected Location requestorLocation = null;
	
	
	private SupportMapFragment supportMapFrament;
	
	/**
	 * 애니메이션 구동을 위한 AnimationDrawable 객체
	 */
	private AnimationDrawable frameAnimation;	

	/**
	 * 요청자 동의 전까지 보여지는 하트 ImageView 객체
	 */
	private ImageView ivWaitingHeart;
	
	/**
	 * GoogleMap 객체
	 */
	private GoogleMap googleMap;	
	
	/**
	 * 애니메이션 ImageView 객체
	 */
	private ImageView ivWaitingAni;
	
	/**
	 * 약속 시간 TextView 객체
	 * 
	 */
	private TextView tvPromiseDate;
	
	/**
	 * 현재 시간 TextView 객체
	 */
	private TextView tvCurrentDate;
	
	/**
	 * 
	 */
	private Handler timerHadler;
	
	private boolean isLoadingTask;
	
	private boolean isShowMap;
	
	private Marker requestorMarker;
	
	private Marker myMarker;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_waiting_recipient);
		
		matchingRequestSeq = getIntent().getIntExtra("matchingRequestSeq", -1);
		Log.d(TAG, "matchingRequestSeq["+matchingRequestSeq+"]");
		
		ivWaitingAni = (ImageView) this.findViewById(R.id.iv_waiting_ani);
		ivWaitingHeart = (ImageView) this.findViewById(R.id.iv_waiting_heart);
		tvPromiseDate = (TextView) this.findViewById(R.id.tv_promise_date);
		tvCurrentDate = (TextView) this.findViewById(R.id.tv_current_date);
		
		//하단 애니메이션 시작
		ivWaitingAni.setBackgroundResource(R.anim.waiting_animation);
		frameAnimation = (AnimationDrawable) ivWaitingAni.getBackground();
		frameAnimation.start();		
		
		init(this, C.MENU_ID_RECIPIENT_WAITING);
		
		//맵관련 변수 초기화
		supportMapFrament = ((SupportMapFragment) getSupportFragmentManager()	.findFragmentById(R.id.map));
		googleMap =supportMapFrament.getMap();
		
		//일단 맵감추고 시작
		supportMapFrament.getView().setVisibility(View.GONE);
		ivWaitingHeart.setVisibility(View.VISIBLE);
		
		new MatchingRequestInfoTask().execute();
	}	
	
	@Override
	protected void onPause(){
		super.onPause();
		if(timerHadler != null){
			timerHadler.removeMessages(0);
		}	
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		if(timerHadler != null){
			timerHadler.sendEmptyMessage(0);
		}
	}
	
	@Override
	public void onBackPressed(){
		Toast.makeText(this, R.string.toast_msg_promise_waiting, Toast.LENGTH_SHORT).show();
	}	

	@Override
	public void onClick(View view) {
		switch(view.getId()){
			case R.id.btn_waiting_profile:
				if(profileYn.equals("Y") ){
					Intent intent = new Intent(this, ProfileActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("profileId", requestorId);
					startActivity(intent);
				}else{
					new CustomAlertDialogBuilder(WaitingRecipientActivity.this, R.string.alert_title, R.string.alert_msg_profile).create();
				}
				break;
		}
		
	}		
	
	private void initMap(){
		ivWaitingHeart.setVisibility(View.GONE);
		supportMapFrament.getView().setVisibility(View.VISIBLE);
		
		if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS && myLocation != null && requestorLocation != null){
			
			LatLng position = new LatLng(requestorLocation.getLatitude(), requestorLocation.getLongitude());
			googleMap = ((SupportMapFragment) getSupportFragmentManager()	.findFragmentById(R.id.map)).getMap();
			
			//맵 위치이동.
			googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
			
			
			MarkerOptions markerOptions = new MarkerOptions();
			markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_another));
			markerOptions.position(new LatLng(requestorLocation.getLatitude(), requestorLocation.getLongitude()));
			requestorMarker = googleMap.addMarker(markerOptions);
			requestorMarker.showInfoWindow();
			
			markerOptions = new MarkerOptions();
			markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
			markerOptions.position(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
			myMarker = googleMap.addMarker(markerOptions);			
			myMarker.showInfoWindow();
			
			isShowMap = true;
		}
	}
	
	private void moveMarker(){
		requestorMarker.setPosition(new LatLng(requestorLocation.getLatitude(), requestorLocation.getLongitude()));
		myMarker.setPosition(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
	}
	

	private void showExpirePromiseDate(){
		new CustomAlertDialogBuilder(this)
		.setTitle(this.getString(R.string.alert_title))
		.setMessage(getString(R.string.alert_msg_expire_promise))
		.setCancelable(false)
		.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				dialog.dismiss();
				WaitingRecipientActivity.this.finish();
				
			}
		})
		.create();				
	}	
	
	private void executeAcceptYnTask(){
		new MatchingAcceptYnTask().execute();
	}
	
	private void executeLocationTask(){
		new RequestorLocationTask().execute();
		
	}
	
	/**
	 * 매칭 정보 가져오는 Task 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private class MatchingRequestInfoTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			showProgress();
		}
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			MatchingInfoResultVo resultVo = null;
			try{
				MatchingLib lib = new MatchingLib();
				
				//요청자 동의 여부
				MatchingAcceptYnResultVo vo = (MatchingAcceptYnResultVo) lib.matchingAcceptYn(matchingRequestSeq, myApp.id);
				if(vo != null) matchingAcceptYn = vo.getMatchingAcceptYn();
				
				//매칭 정보 가져오기
				resultVo = (MatchingInfoResultVo) lib.matchingRequestInfo(matchingRequestSeq, Double.toString(myLocation.getLatitude()), Double.toString(myLocation.getLongitude()));
				
			}catch(Exception e){
				e.printStackTrace();
				resultVo = null;
			}
			return resultVo;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			closeProgress();
			MatchingInfoResultVo vo = (MatchingInfoResultVo) resultVo;
			if(vo == null || vo.getResult().equals(C.API_RESULT_VALUE_FAIL)){
				Log.d(TAG, "MatchingInfoResultVo null......");
				new CustomAlertDialogBuilder(WaitingRecipientActivity.this, R.string.alert_title, R.string.alert_msg_exception).create();
				WaitingRecipientActivity.this.finish();
				
			}else{
				//약속시간 
				promiseDate = Util.getCalendar(vo.getPromiseDate());
				
				SimpleDateFormat formatter = new SimpleDateFormat("hh:mm", Locale.ENGLISH);
				tvPromiseDate.setText(formatter.format(promiseDate.getTime()));				

				//프로파일 보여주기 여부
				profileYn = vo.getProfileYn();
				
				//요청자 아이디
				requestorId = vo.getId();
				
				//타이머 돌리기 시작
				timerHadler = new TimerHandler(WaitingRecipientActivity.this);
				timerHadler.sendEmptyMessage(0);
				Log.d(TAG, "timerHadler......................");
				
			}
			
		}
		
	}	
	
	/**
	 * 요청자 동의 체크 Task 클래스 
	 * 
	 * @author Administrator
	 *
	 */
	private class MatchingAcceptYnTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			isLoadingTask = true;
		}
		
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			MatchingAcceptYnResultVo libResultVo = null;
			try{
				MatchingLib lib = new MatchingLib();
				libResultVo = (MatchingAcceptYnResultVo) lib.matchingAcceptYn(matchingRequestSeq, myApp.id);
				
			}catch(Exception e){
				e.printStackTrace();
			}
			return libResultVo;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			MatchingAcceptYnResultVo vo = (MatchingAcceptYnResultVo) resultVo;
			if(vo != null){
				matchingAcceptYn = vo.getMatchingAcceptYn();
				if(matchingAcceptYn.equals("Y")){
					//요청자 수락시 map 보여줌
					executeLocationTask();
				}
			}
			isLoadingTask = false;
			
		}
	}
	
	/**
	 * 요청자 위치 정보 가져오는 Task 클래스
	 * @author Administrator
	 *
	 */
	private class RequestorLocationTask extends AsyncTask<Void, Void, LibResultVo> {
		
		@Override
		protected void onPreExecute() {
			isLoadingTask = true;
		}		
		
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			MemberLastLocationResultVo resultVo = null;
			try{
				resultVo = (MemberLastLocationResultVo) new MemberLib().memberLastLocation(requestorId);
			}catch(Exception e){
				e.printStackTrace();
			}
			return resultVo;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			MemberLastLocationResultVo vo = (MemberLastLocationResultVo) resultVo;
			if(vo != null){
				if(requestorLocation == null) requestorLocation = new Location("dummyprovider");
				requestorLocation.setLatitude(vo.getLatitude());
				requestorLocation.setLongitude(vo.getLongitude());
				
				if(isShowMap){
					//이미 지도가 보여지고 잇을때 마커만 변경
					moveMarker();
				}else{
					initMap();
				}
				
			}
			isLoadingTask = false;
		}
		
	}
	
	
	
	/**
	 * 현재시간과 대기시간 출력 Handler 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private static class TimerHandler extends Handler{
		SimpleDateFormat formatter = new SimpleDateFormat("a hh:mm", Locale.ENGLISH);
		WaitingRecipientActivity activity;
		int currentSec;
		boolean finish = false;
		public TimerHandler(WaitingRecipientActivity activity){
			this.activity = activity;
			this.currentSec = 0;
		}
		
		public void handleMessage(Message msg){
			currentSec++;
			
			//현재시간 셋팅
			activity.tvCurrentDate.setText(formatter.format(new Date()));
			
			//요청자 수락 여부 체크
			if(currentSec%5 == 0 && !activity.isLoadingTask && activity.matchingAcceptYn.equals("N")){
				activity.executeAcceptYnTask();
			}
			
			//요청자 위치 조회
			if(activity.matchingAcceptYn.equals("Y")){
				if(currentSec%5 == 0 && !activity.isLoadingTask){
					activity.executeLocationTask();
				}
			}
			
			//약속시간 초과시 
			if(activity.promiseDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() < 0 && !finish){
				
				activity.showExpirePromiseDate();
				this.removeMessages(0);
				finish = true;
				
			}
			
			this.sendEmptyMessageDelayed(0,1000);
		}		
	}

}
